/**
 * 首页中间的view
 * 由 WangYu 创建
 * 日期 2017/9/27
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    ART,
    Dimensions, Image,
} from 'react-native';
import {themeColor} from "../../util/Config";
import {Actions} from "react-native-router-flux";
import Slider from "../../view/Slider";
import DashedLine from "../../view/DashedLine";
import Button from "../../view/Button";
import CommonUtil from "../../util/CommonUtil";
import Api from "../../util/Api";
import Toast from "teaset/components/Toast/Toast";
import NetUtils from "../../util/NetUtils";
import Spinner from "../../view/Spinner";
import AuthorityManager from "../authority/AuthorityManager";
let screenWidth = Dimensions.get('window').width;
export default class HomeMiddleView extends Component {

    constructor(props) {
        super(props);
        this.state={
            loanValue:this.props.data.object.minAmount,
            repayAmount:0,
            status:'',
            progressVisible:false,
        }
    }

    componentWillReceiveProps(next) {
        let data = next.data.object;
        this.setState({
            status: data.status,
        })
    }

    componentDidMount() {
        this.onProgressChange(this.props.data.object.minAmount);
    }

    /**
     * remainStep : [50,70,60,30]
     * status : APPLYING
     * NO_APPLY:未申请;
     * APPLYING:申请中;
     * 这两个说明授权的步骤还没走完
     * PENDING:待审批;
     * APPROVAL:审批中;
     * 这两个说明风控正在审核。。需要时间等待
     * APPROVED_SUCCESS:审批通过; 这个是风控通过了，可以去借款了
     * APPROVED_REFUSED:审批拒绝; 这是风控拒绝。
     * WAIT_PAY:"等待放款",
     * PAY_PROCESSING:"放款处理中",
     * PAY_SUCCESS:"放款成功，还款中"
     * OVERDUE:"已逾期"
     * RE_APPLY:"二次借款"
     */
    getStatusText(status) {
        if (!this.statusMap) {
            let map = new Map();
            map.set("NO_APPLY", '立即申请开户');
            map.set("APPLYING", '继续授权');
            map.set("PENDING", '待审批');
            map.set("APPROVAL", '审批中');
            map.set("APPROVED_SUCCESS", '审批通过,去签约');
            map.set("APPROVED_REFUSED", '审批拒绝');
            map.set("WAIT_PAY", '等待放款');
            map.set("PAY_PROCESSING", '放款处理中');
            map.set("PAY_SUCCESS", '放款成功');
            map.set("OVERDUE", '已逾期');
            map.set("RE_APPLY", '再次借钱');
            this.statusMap = map;
        }
        this.statusMap.set("REFUSED", "审批拒绝,请" + this.props.data.object.day + "天后再来");
        return this.statusMap.get(status);
        // return ',请' + this.props.data.object.day + '天后再来';
    }

    render() {
        let data = this.props.data.object;
        let minAmount = parseInt(data.minAmount);
        let maxAmount = parseInt(data.maxAmount);
        return (
            <View style={[this.props.style, styles.container]}>
                <Text onPress={() => Actions.Test()} style={{marginTop: 10, color: 'black', fontSize: 16}}>申请贷款额度</Text>
                <Text style={{marginTop: 8, color: themeColor, fontSize: 30}}>{this.state.loanValue}</Text>
                <Slider
                    style={{alignSelf: 'stretch', marginLeft: 20, marginRight: 20,}}
                    trackStyle={{height: 6, borderRadius: 10, backgroundColor: '#f5f5f5'}}
                    minimumTrackTintColor={themeColor}
                    thumbImage={require('../../../images/sbo.png')}
                    thumbStyle={styles.thumb}
                    step={100}
                    minimumValue={minAmount}
                    maximumValue={maxAmount}
                    value={minAmount}
                    onValueChange={this.onProgressChange}
                />
                <View style={styles.minMax}>
                    <Text>{minAmount}</Text>
                    <Text>{maxAmount}</Text>
                </View>
                <DashedLine width={screenWidth - 40} style={{marginTop: 10}}/>
                <View style={styles.itemStyle}>
                    <Text>借款期限:</Text>
                    <Text>{parseInt(data.minPeriod) + (data.periodUnit === 'DAY' ? '天' : '月')}</Text>
                </View>
                <DashedLine width={screenWidth - 40}/>
                <View style={styles.itemStyle}>
                    <Text>到期应还:</Text>
                    <Text>{this.state.repayAmount}元</Text>
                    <Text style={{position: 'absolute', right: 10, color: themeColor}}>费率查询</Text>
                </View>
                <DashedLine width={screenWidth - 40}/>
                <Button title={this.getStatusText(this.state.status)}
                        style={{marginLeft: 10, marginRight: 10, marginTop: 30}}
                        onPress={() => this.onBtnPress()}/>
                <Spinner cancelable={true} visible={this.state.progressVisible} textContent={"加载中..."}
                         textStyle={{color: '#FFF'}}/>
            </View>
        );
    }

    onBtnPress() {
        if (!Api.isLogin) {
            Actions.LoginPage();
            return;
        }
        this.setState({progressVisible: true});
        NetUtils.post(Api.getStep, null, result => {
            if (result.code === 1 && result.object) {
                let status = result.object.status;
                this.setState({
                    status: status,
                    progressVisible: false
                });
                switch (status) {
                    case "NO_APPLY":
                    case "APPLYING":
                        if (result.object.remainStep && result.object.remainStep.length > 0) {
                            //授权没有完成
                            Api.stepArr=result.object.remainStep;
                            //开启授权
                            AuthorityManager.startNextStep();
                        } else {
                            Toast.message("授权列表为空,但状态为申请中,请联系客服");
                        }
                        break;
                    case "PENDING":
                        // 待审批，
                        Toast.message("请耐心等待审批完成");
                        break;
                    case "APPROVAL":
                        // 审批中
                        Toast.message("小微正在努力审批,马上就好,请耐心等待");
                        break;
                    case "APPROVED_SUCCESS":
                        //审批通过
                        // ActivityUtils.startActivity(mView.getContext(), SignContractActivity.class);
                        break;
                    case "APPROVED_REFUSED":
                        Toast.message("您的借款申请已经被拒绝,请" + this.props.data.object.day + "天后再来申请");
                        break;
                    case "WAIT_PAY":
                    case "PAY_PROCESSING":
                        //   :"等待放款",:"放款处理中",
                        Toast.message("签约已完成，请耐心等待放款");
                        break;
                    case "PAY_SUCCESS":
                        Toast.message("放款成功，请结清后再来申请");
                        break;
                    case "REFUSED":
                        Toast.message("您的借款申请已经被拒绝,请" + result.object.day + "天后再来申请");
                        break;
                    case "OVERDUE":
                        Toast.message("您已经逾期，请及时还款");
                        break;
                    case "RE_APPLY":
                        // showReLoanConfirmDialog();
                        break;
                    default:
                        Toast.message("未知状态");
                }
            }
        });

    }


    onProgressChange = (loanMoney) => {
        let data = this.props.data.object;
        let serviceRate = data.rate - 1;
        let date = data.minPeriod;
        let lixi = CommonUtil.fmoney(loanMoney * serviceRate * date, 2);
        if (data.periodUnit === "DAY") {
            lixi /= 30.0;
        }
        this.setState({
            loanValue: CommonUtil.fmoney(loanMoney, 2),
            repayAmount: CommonUtil.fmoney(loanMoney + lixi, 2),
        })
    }

}

const styles = StyleSheet.create({
    container: {
        backgroundColor: 'white',
        marginLeft: 10,
        marginRight: 10,
        marginTop: 10,
        height: 320,
        borderRadius: 10,
        alignItems: 'center'
    },
    thumb: {
        width: 18,
        height: 24,
        shadowColor: 'transparent',
        backgroundColor: 'transparent',
        shadowOffset: {width: 0, height: 1},
        shadowOpacity: 0.5,
        shadowRadius: 1,
    },
    minMax: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignSelf: 'stretch',
        paddingLeft: 10,
        paddingRight: 10,
    },
    itemStyle: {
        flexDirection: 'row',
        height: 40,
        alignItems: 'center',
        justifyContent: 'flex-start',
        alignSelf: 'stretch',
        paddingLeft: 10,
        paddingRight: 10,
    }
});
